﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Buffers;

namespace _4_6WebAPIFramework
{
    class Program
    {
        static void Main(string[] args)
        {

        }


        async Task ProcessLinesAsync(File stream)
        {
            byte[] buffer = ArrayPool<byte>.Shared.Rent(1024);
            var bytesBuffered = 0;
            var bytesConsumed = 0;

            while (true)
            {
                // 在buffer中计算中剩余的字节数
                var bytesRemaining = buffer.Length - bytesBuffered;

                if (bytesRemaining == 0)
                {
                    // 将buffer size翻倍 并且将之前缓冲的数据复制到新的缓冲区
                    var newBuffer = ArrayPool<byte>.Shared.Rent(buffer.Length * 2);
                    Buffer.BlockCopy(buffer, 0, newBuffer, 0, buffer.Length);
                    // 将旧的buffer丢回池中
                    ArrayPool<byte>.Shared.Return(buffer);
                    buffer = newBuffer;
                    bytesRemaining = buffer.Length - bytesBuffered;
                }

                var bytesRead = await stream.ReadAsync(buffer, bytesBuffered, bytesRemaining);
                if (bytesRead == 0)
                {
                    // EOF 末尾
                    break;
                }

                // 跟踪已缓冲的字节数
                bytesBuffered += bytesRead;

                do
                {
                    // 在缓冲数据中查找找一个行末尾
                    linePosition = Array.IndexOf(buffer, (byte)'\n', bytesConsumed, bytesBuffered - bytesConsumed);

                    if (linePosition >= 0)
                    {
                        // 根据偏移量计算一行的长度
                        var lineLength = linePosition - bytesConsumed;

                        // 处理这一行
                        ProcessLine(buffer, bytesConsumed, lineLength);

                        // 移动bytesConsumed为了跳过我们已经处理掉的行 (包括\n)
                        bytesConsumed += lineLength + 1;
                    }
                }
                while (linePosition >= 0);
            }
        }
    }
}
